package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.bean.DataObject;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ricky
 * @date 2021/6/9
 */
public class Latest extends BaseFn {
    @Override
    public Object call(Object[] arguments, FelContext context) {
        String filterZdmc = String.valueOf(arguments[0]);
        String valZdmc = String.valueOf(arguments[1]);
        boolean isWb = false;
        if (arguments.length == 3) {
            isWb = (Boolean) arguments[2];
        }
        DataObject data = (DataObject) context.get("$data");

        if (data == null) {
            throw new AppException("未找到对应的实体对象，请在规则节点中检查实体名称是否配置正确");
        }

        String stbm = filterZdmc.split("\\.")[0];

        List<DataObject> collect = data.getCbsj().stream().filter(item -> item.getStbm().equals(stbm)).collect(Collectors.toList());

        List<String> logs = service.getGzjyLog().getLogs();
        DataObject currDataObject = null;
        Date maxDate = DateUtil.parse("1970-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
        for (DataObject dataObject : collect) {
            DataObject.ZdItemDTO zd = getZd(dataObject, filterZdmc);
            if (zd == null) {
                continue;
            }
            String zdValue = (String) GetValue.getZdValue(zd, false, logs);
            if (StringUtils.isBlank(zdValue)) {
                continue;
            }
            Date date = DateUtil.parse(zdValue, "yyyy-MM-dd HH:mm:ss");
            if (date.after(maxDate)) {
                maxDate = date;
                currDataObject = dataObject;
            }
        }
        if (currDataObject == null) {
            logs.add("未找到最新数据，返回：''");
            return "";
        }
        DataObject.ZdItemDTO zd = getZd(currDataObject, valZdmc);
        return GetValue.getZdValue(zd, isWb, logs);
    }

    @Override
    public String getZwmc() {
        return "获取最新一条数据";
    }

    @Override
    public List<Param> getParams() {
        List<Param> paramList = new ArrayList<>();
        paramList.add(new Param("filterZdmc"));
        paramList.add(new Param("valZdmc"));
        paramList.add(new Param("isWb", "boolean", false));
        return paramList;
    }


    @Override
    public String getName() {
        return "latest";
    }
}
